package com.cch.cooperation.common.web.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class RequestUtil {

    private static final String TOKEN_KEY = "Authorization";
    private static final String DEVICE_ID_KEY = "cid";
    private static final String DEVICE_TOKEN_KEY = "deviceToken";
    private static final String UNKNOWN = "unknown";

    public static String getDeviceId(HttpServletRequest request) {
        return request.getHeader(DEVICE_ID_KEY);
    }

    public static String getDeviceToken(HttpServletRequest request) {
        return request.getHeader(DEVICE_TOKEN_KEY);
    }

    public static String getAccessToken(HttpServletRequest request) {
        // 从请求头中获取
        String accessToken = request.getHeader(TOKEN_KEY);
        // 从 cookie 中获取
        if (StrUtil.isEmpty(accessToken)) {
            Cookie[] cookies = request.getCookies();
            if (ArrayUtil.isNotEmpty(cookies)) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(TOKEN_KEY)) {
                        accessToken = cookie.getValue();
                        break;
                    }
                }
            }
        }
        // 从请求参数中获取
        if (StrUtil.isEmpty(accessToken)) {
            accessToken = request.getParameter(TOKEN_KEY);
        }
        return accessToken;
    }

    public static String getIp(HttpServletRequest request) {
        if (request == null) {
            return UNKNOWN;
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }
}
